//
//  ChangeNameViewController.swift
//  Gaoloumi
//
//  Created by Jasper on 4/13/16.
//  Copyright © 2016 Jasper. All rights reserved.
//

import UIKit
import SVProgressHUD
import AVOSCloud

fileprivate func < <T : Comparable>(lhs: T?, rhs: T?) -> Bool {
  switch (lhs, rhs) {
  case let (l?, r?):
    return l < r
  case (nil, _?):
    return true
  default:
    return false
  }
}


class ChangeNameViewController: RootViewController, UITextFieldDelegate {

    
    @IBOutlet weak var viewHeight: NSLayoutConstraint!
    
    @IBOutlet weak var nameTextField: UITextField!
    
    @IBOutlet weak var saveButton: UIButton!
    
    
    let contantHeight = UIScreen.main.bounds.height-64+1
 
    override func viewDidLoad() {
        super.viewDidLoad()

        saveButton.layer.cornerRadius = 5
        saveButton.layer.masksToBounds = true
        
        viewHeight.constant = contantHeight
        
        nameTextField.text = AVUser.current().username
  
    }
    @IBAction func gestureTap(_ sender: UITapGestureRecognizer) {
        nameTextField.resignFirstResponder()
    }

    @IBAction func saveButtonClicked(_ sender: UIButton) {
        
        if nameTextField.text == AVUser.current().username {
            SVProgressHUD.showError(withStatus: "请输入新用户名")
            return
        }
        
        if nameTextField.text?.characters.count < 2 {
            SVProgressHUD.showError(withStatus: "请输入3-15个字")
            return
        }
        
        SVProgressHUD.show(withStatus: "保存用户名...")
        AVUser.current().username = nameTextField.text
        AVUser.current().fetchWhenSave = true
        AVUser.current().saveInBackground { (succed: Bool, error: Error?) in
            if succed {
                SVProgressHUD.dismiss()
                self.navigationController?.popViewController(animated: true)
            } else {
                SVProgressHUD.showSuccess(withStatus: error?.localizedDescription)
            }
        }
    }

    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        if (textField.text?.characters.count)! + string.characters.count > 10 {
            SVProgressHUD.showError(withStatus: "最多输入15个字")
            return false
        }
        return true
    }

}
